<template>
  <div>
    <Row style="text-align: left;">
      <i-col span="24">
        <Alert type="warning" show-icon style="margin:1rem 0.5rem;">
          <span style="color:red;">上传过程中关闭此页面会导致上传失败!!!!</span>
          <template slot="desc">
            例如 D://products/2022-02-08/528744347078/****.jpg, 则上传图片时,应该选择目录2022-02-08目录即可,这样会自动将该目录下的所有产品图片上传.
          </template>
        </Alert>
        <Row >
          <i-col :span="24">
            <label>
              <input ref="fileSelector" type="file" @change="fileListSelected()" accept=".png, .jpg, .jpeg"
                     directory webkitdirectory mozdirectory allowdirs multiple style="display: none;"></input>
              <Button type="primary" size="large" icon="md-images" @click="selectImages()" :disabled="isBatchUploading">选择图片</Button>
            </label>
          </i-col>
          <Divider></Divider>
          <i-col :span="24" style="text-align: left;" v-show="canUpload">
            <Button type="success"  icon="md-cloud-upload" @click="uploadFileItems()" :disabled="!canUpload" >点我上传全部图片</Button>
            <Button type="error"  icon="md-close" @click="clearFileItems()" :disabled="isBatchUploading || fileItemList.length == 0" style="margin-left: 10px;">清空待导入图片</Button>
          </i-col>
        </Row>

        <div style="margin-top: 1rem"  v-show="isBatchUploading || successCount>0">
          <Progress :percent="(successCount/fileItemList.length)*100">
            <Icon type="checkmark-circled"></Icon>
            <span>{{successCount}}/{{fileItemList.length}}</span>
          </Progress>
        </div>

        <List style="margin-top: 30px;" size="small" border>
          <ListItem v-for="(item, index) in fileItemList" v-if="showAll || isTopRows(index)" :style="{backgroundColor:index%2===0?'#fafafa':''}">
            <ListItemMeta>
              <template slot="title">
                <span style="margin-right: 1rem">#{{index+1}} </span>
                <span>{{item.file.webkitRelativePath}}</span>
              </template>
            </ListItemMeta>
            <div slot="extra">
              <Button type="text" size="small" v-if="isWaiting(item.state)">
                <span style="color: #2db7f5;">等待上传</span>
              </Button>
              <Button type="text" loading v-if="isUploading(item.state)"></Button>
              <Button type="text" size="small" v-if="isSuccess(item.state)">
                <Icon type="md-checkmark" color="#19be6b"></Icon>
                <span style="color: #19be6b">完成</span>
              </Button>
              <Button type="text" size="small" v-if="isFailed(item.state)">
                <Icon type="md-close" color="#ed4014"></Icon>
                <span style="color: #ed4014">失败</span>
              </Button>
              <Button type="text" size="small" icon="md-refresh" @click="reUploadFileItem(item)" v-if="isFailed(item.state)">重新上传</Button>
            </div>
          </ListItem>
          <div style="margin-top: 10px; text-align: right;">
            <Button type="text" size="small" :icon="showAll?'ios-arrow-up':'ios-arrow-down'" @click="showAll = !showAll" v-if="fileItemList.length > showMinRows">{{showAll?"收起":"显示全部"}}</Button>
          </div>
        </List>
      </i-col>
    </Row>
  </div>
</template>

<script>
import ApiBase from "../../api/moudles/ApiBase";
import axios from "axios";

export default {
  name: "ImagesUpload",
  data() {
    return {
      uploadUrl: this.$apiImpProduct.getUploadUrl(),
      successCount: 0,
      fileItemList: [],
      uploadStates: {
        waiting: 0,
        uploading: 1,
        success: 2,
        failed: 3,
      },
      isBatchUploading: false,
      canUpload: false,
      showMinRows: 10,
      showAll: false,
    }
  },
  methods: {
    selectImages() {
      this.$refs.fileSelector.click();
    },
    fileListSelected() {
      this.fileItemList.splice(0);
      let files = this.$refs.fileSelector.files;
      let regex = /\.(jpg|gif|png)$/i;
      for(let i=0; i<files.length; i++) {
        if(regex.test(files[i].name)) {
          this.fileItemList.push({state: this.uploadStates.waiting, file: files[i]});
        }
      }
      // console.log(this.fileItemList);
      this.canUpload = this.fileItemList.length > 0;
      this.showAll = false;
      this.successCount = 0;
    },
    clearFileItems() {
      this.fileItemList.splice(0);
      this.successCount = 0;
      this.canUpload = false;
      this.showAll = false;
      this.isBatchUploading = false;
      this.$refs.fileSelector.value = "";
    },
    uploadFileItems() {
      if(this.fileItemList.length > 0) {
        this.canUpload = false;
        this.isBatchUploading = true;
        this.uploadFileItem(0);
      }else{
        this.$Message.error({content: "未选择图片", duration: 3});
      }
    },
    uploadFileItem(index) {
      if(index < this.fileItemList.length) {
        let item = this.fileItemList[index];
        let formData = new FormData();
        formData.append("file", item.file, item.file.name);
        formData.append("requestMsg", this.getUploadParam(item.file.webkitRelativePath));
        item.state = this.uploadStates.uploading;
        axios.post(this.uploadUrl, formData).then(response => {
          if(response.data.success) {
            item.state = this.uploadStates.success;
            this.successCount++;
          }else{
            item.state = this.uploadStates.failed;
          }
          this.uploadFileItem(++index);
        }).catch(() => {
          item.state = this.uploadStates.failed;
          this.uploadFileItem(++index);
        });
      }else{
        this.canUpload = true;
        this.isBatchUploading = false;
      }
    },
    reUploadFileItem(item) {
      let formData = new FormData();
      formData.append("file", item.file, item.file.name);
      formData.append("requestMsg", this.getUploadParam(item.file.webkitRelativePath));
      item.state = this.uploadStates.uploading;
      axios.post(this.uploadUrl, formData).then(response => {
        if(response.data.success) {
          item.state = this.uploadStates.success;
          this.successCount++;
        }else{
          item.state = this.uploadStates.failed;
        }
      }).catch(() => {
        item.state = this.uploadStates.failed;
      });
    },
    getUploadParam(path) {
      let fileParam = {
        isMultiProducts: true,
        webkitRelativePath: path,
      };
      let requestMsg = ApiBase.createRequestMsg(fileParam);
      return JSON.stringify(requestMsg);
    },
    isWaiting(state) {
      return state == this.uploadStates.waiting;
    },
    isUploading(state) {
      return state == this.uploadStates.uploading;
    },
    isSuccess(state) {
      return state == this.uploadStates.success;
    },
    isFailed(state) {
      return state == this.uploadStates.failed;
    },
    isTopRows(index) {
      return index < this.showMinRows;
    }
  }
}
</script>

<style scoped lang="less">
.loading-icon {
  animation: ani-demo-spin 1s linear infinite;
}
</style>
